package com.ecpbm.controller;

import com.ecpbm.pojo.Type;
import com.ecpbm.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @PACKAGE_NAME: com.ecpbm.controller
 * @CLASS_NAME: TypeController
 * @USER: kagura
 * @Description TODO
 * @Date 2021/4/17 1:01 下午
 * @MONTH_NAME_FULL: 四月
 * @DAY: 17
 * @DAY_NAME_FULL: 星期六
 * @PROJECT_NAME: ecpbm
 **/
@Controller
@RequestMapping("/type")
public class TypeController {

    @Autowired
    private TypeService typeService;

    @RequestMapping("getType/{flag}")
    @ResponseBody
    public List<Type> getType(@PathVariable("flag") Integer flag) {
        // 获取序所有商品类型列表
        List<Type> typeList = typeService.getAll();
        if (flag == 1) {
            Type t = new Type();
            t.setId(0);
            t.setName("请选择...");
            typeList.add(0, t);
        }
        return typeList;
    }

    // 获取所有类型
    @RequestMapping(value = "getAllType")
    @ResponseBody
    public List<Type> getAllType() {
        List<Type> typeList = typeService.getAll();
        return typeList;
    }

    // 添加商品类型
    @RequestMapping(value = "addType", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String addType(Type type) {
        try {
            typeService.addType(type);
            return "{\"success\": \"true\", \"message\": \"类型添加成功\"}";
        } catch (Exception e) {
            return "{\"success\": \"false\", \"message\": \"类型添加失败\"}";
        }
    }

    // 修改商品类型
    @RequestMapping(value = "editType", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String editType(Type type) {
        try {
            typeService.updateType(type);
            return "{\"success\": \"true\", \"message\": \"类型修改成功\"}";
        } catch (Exception e) {
            return "{\"success\": \"false\", \"message\": \"类型修改失败\"}";
        }
    }

    // 删除商品类型及类型下的所有商品
    @RequestMapping(value = "removeType", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String deleteType(@RequestParam("id") String id) {
        try {
            int result = typeService.deleteType(Integer.parseInt(id.substring(0, id.length() - 1)));
            if (result > 0) {
                return "{\"success\": \"false\", \"message\": \"类型删除成功\"}";
            } else {
                return "{\"success\": \"false\", \"message\": \"类型删除失败\"}";
            }
        } catch (Exception e) {
            return "{\"success\": \"false\", \"message\": \"类型删除失败\"}";
        }
    }
}
